package cuiyt.offer;

import org.junit.Test;

/**
 * @author cyt
 * @create 2020-05-30 14:50
 */
public class T34 {


    /**
     * 字符串的序列化， 反序列化
     *
     * @param root
     * @return
     */
    @Test
    String Serialize(TreeNode root) {
        if (root == null) {
            return "";
        }
        StringBuilder sb = new StringBuilder();
        se(root, sb);
        return sb.toString();
    }

    void se(TreeNode root, StringBuilder sb) {
        if (root == null) {
            sb.append("#,");
            return;
        }
        sb.append(root.val);
        sb.append(",");
        se(root.left, sb);
        se(root.right, sb);
    }

    int index = -1;

    @Test
    TreeNode Deserialize(String str) {
        if (str.length() == 0) return null;
        String[] strings = str.split(",");
        return De(strings);
    }

    @Test
    TreeNode De(String[] str) {
        index++;
        // 非空
        if (!str[index].equals("#")) {
            TreeNode node = new TreeNode(0);
            node.val = Integer.parseInt(str[index]);
            node.left = De(str);
            node.right = De(str);
            return node;
        }
        // 空
        return null;
    }

}
